//
//  ViewController.swift
//  HCSDK
//
//  Created by chenzhen on 03/05/2024.
//  Copyright (c) 2024 chenzhen. All rights reserved.
//

import UIKit
import HCSDK
import HCTherapy
import HCSchedule

class ViewController: UIViewController {
    
    let channelCode = "appauth2022666"
    lazy var therapyApi = TherapyApi()

    lazy var scheduleApi = ScheduleApi()
    
    lazy var taskApi = TaskApi()
    
    let user =  User()
        
    lazy var btn = {
        let btn = UIButton(frame: .init(x: 0, y: 0, width: 120, height: 45))
        btn.backgroundColor = .purple
        btn.setTitle("login", for: .normal)
        btn.addTarget(self,
                      action: #selector(onPressedLogin),
                      for: .touchUpInside)
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.title = "登录"
        self.view.addSubview(btn)
        self.btn.center = self.view.center
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "reset",
                                                                 style: .plain,
                                                                 target: self,
                                                                 action: #selector(reset))
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    }
}

extension ViewController {
    @objc nonisolated func onPressedLogin() {
        Task {
            do{
                let userName = User().userID
                try await HCSDK.instance.login(userName,mode: .Customized)
                let api = TherapyApi()
                guard let cures = try await api.fetchCures(userName),
                      !cures.isEmpty
                else {
                    return
                }
                debugPrint(cures)
                DispatchQueue.main.async {
                    let vc = CureTableViewController(cures: cures)
                    self.navigationController?.pushViewController(
                        vc, animated: true
                    )
                }
                
            } catch {
                debugPrint(error)
            }
        }
    }
    
    @objc func reset() {
        HCSDK.instance.reset()
    }
}

